<?php

namespace app\index\controller;

use app\index\model\Gsrecord;
use app\index\model\Member;
use app\index\model\Station;
use think\Controller;

/**
 * Created by PhpStorm.
 * User: jieai
 * Date: 2017-07-16
 * Time: 20:21
 */
class GsrecordController extends Controller
{
	public function index()
	{

		return $this->fetch();
	}

	public function getlist()
	{if (input('stime')&&input('dtime')){
        $record = Gsrecord::with('members,station,Gsvalue')->whereTime('starttime','between',[input('stime'),input('dtime')])->order('starttime desc')->select();
    }
    else{
        $record = Gsrecord::with('members,station,Gsvalue')->order('starttime desc')->select();
    }




		return json(['data' => $record]);
	}

	public function addgs()
	{$id=input('id');
		if ($id) {

			$record=Gsrecord::with('members,station,Gsvalue')->find($id);
			$this->assign('record',$record);
			$gsvalue= $record->Gsvalue()->field('member_id,gsvalue')->select();

			$this->assign('gsvalue2',$gsvalue);


		}
		$stationlist = $this->getstations();
		$this->assign('stationlist', $stationlist);
		$this->getmembers();
		return $this->fetch();

	}

	protected function getstations()
	{
		$record = Station::all();
		return $record;
	}

	protected function getmembers()
	{
		$record = Member::all();
		$this->assign('memberlist', $record);
	}

    /**
     *
     */
    public function postaddgs()
	{
//    dump(input());
		$id=input('recordid');

		if ($id) {
			$newrecord=Gsrecord::get($id);

		}else{
			$newrecord = new Gsrecord();
			$newrecord->pend = 0;
		}

		$newrecord->station_id = input('station');
		$newrecord->content = input('content');
		$newrecord->starttime = input('dates');
		$newrecord->donetime = input('datee');

		$members = input('members/a');
		if (!$members) {
			return $this->error('人员不能为空');
		}
		$gsvalues = input('gsvalue/a');
		if ($newrecord->save()) {
			if ($id) {
				$newrecord->Gsvalue()->delete();
			}
			$membersrecord = array();
			foreach ($members as $key => $item) {
				$membersrecord[] = ['member_id' => $key, 'gsvalue' => $gsvalues[$key]];
			}
			$newrecord->Gsvalue()->saveAll($membersrecord);
			return $this->success('操作成功!即将跳转');

		}
		return $this->error('添加失败');

	}

	public function deletebyid()
	{
		$id=input('id');
		$record=Gsrecord::get($id);
		$record->Gsvalue()->where(['gsrecord_id'=>$id])->delete();
		if (Gsrecord::destroy($id)) {
			return $this->success('删除成功!');
		}
		return $this->error('删除失败');
	}

	public function pendbyid()
	{
		$id=input('id');
		$record=Gsrecord::get($id);
		$record->pend=1;
		if ($record->save()) {
			return $this->success('审核成功!');
		}
		return $this->error('审核失败');

	}
}